package com.yao.yaoojcodesandbox.controller;

import com.yao.yaoojcodesandbox.JavaCodeSandboxTemplate;
import com.yao.yaoojcodesandbox.JavaDockerCodeSandbox;
import com.yao.yaoojcodesandbox.JavaNativeCodeSandbox;
import com.yao.yaoojcodesandbox.model.ExecuteCodeRequest;
import com.yao.yaoojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {

    private static final String AUTH_REQUEST_HEADER = "auth"; //在请求头之间，传递字符串的方式，来鉴别这个字符串是否是服务器预先设定好的

    private static final String AUTH_REQUEST_SECRET = "secretKey"; //设置一个密钥

    @Resource
    private JavaNativeCodeSandbox  javaNativeCodeSandbox;

    @Resource
    private JavaDockerCodeSandbox javaDockerCodeSandbox;

    @GetMapping("/health")
    public String healthCheck(){
        return "ok";
    }

    /**
     * 基于Linux虚拟机的java代码沙箱
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                    HttpServletResponse response) {
        //进行一个基本的权限认证
        String authHeader=request.getHeader(AUTH_REQUEST_HEADER);
        if(!AUTH_REQUEST_SECRET.equals(authHeader)){
            response.setStatus(403);//401一般表示没权限，被禁止 403 表示禁止访问
            return null;
        }
        if(executeCodeRequest==null){
            throw new RuntimeException("请求参数为空");
        }
        return javaNativeCodeSandbox.executeCode(executeCodeRequest);
    }
}
